package com.xunyin.config;


import com.github.wxpay.sdk.WXPayConfig;
import com.xunyin.modules.mtstore.domain.MtStore;
import com.xunyin.modules.mtstore.service.StoreService;
import com.xunyin.utils.RedisUtil;
import com.xunyin.utils.RedisUtils;
import com.xunyin.utils.ShopKeyUtils;
import com.xunyin.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * 微信支付配置类
 * <p>
 * Created by xunyinyunshang <3594419785@qq.com>
 * CopyRight 讯音云商 https://www.tonetn.com
 */
@Configuration
public class WXPayConfigImpl implements WXPayConfig {

    private static final Logger logger = LoggerFactory.getLogger(WXPayConfigImpl.class);

    private String appId;

    private String mchId;

    private String key;

    private String callbackUrl;

    private String certPath;

    private static RedisUtils redisUtils;

    public static StoreService storeService;


    private static WXPayConfigImpl instance = new WXPayConfigImpl();

    @Autowired
    public static WXPayConfigImpl getInstance(String callbackUrl, Integer storeId, RedisUtils redisUtils, StoreService storeService) {
        WXPayConfigImpl.redisUtils = redisUtils;
        WXPayConfigImpl.storeService = storeService;
        instance.appId = RedisUtil.get(ShopKeyUtils.getWxAppAppId());
        instance.mchId = redisUtils.getY(ShopKeyUtils.getWxPayMchId());
        instance.key = redisUtils.getY(ShopKeyUtils.getWxPayMchKey());
        instance.callbackUrl = callbackUrl;
        instance.certPath = redisUtils.getY(ShopKeyUtils.getWxPayKeyPath());

        if (storeId != null && storeId > 0) {
            MtStore mtStore = storeService.queryStoreById(storeId);
            if (mtStore.getWxMchId() != null && StringUtil.isNotEmpty(mtStore.getWxMchId()) && mtStore.getWxApiV2() != null && StringUtil.isNotEmpty(mtStore.getWxApiV2())) {
                instance.mchId = mtStore.getWxMchId();
                instance.key = mtStore.getWxApiV2();
            }
        }

        return instance;
    }

    @Override
    public String getAppID() {
        return appId;
    }

    @Override
    public String getMchID() {
        return mchId;
    }

    @Override
    public String getKey() {
        return key;
    }

    @Override
    public InputStream getCertStream() {
        try {
            File file = new File(certPath);
            return new FileInputStream(file);
        } catch (FileNotFoundException e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    @Override
    public int getHttpConnectTimeoutMs() {
        return 2000;
    }

    @Override
    public int getHttpReadTimeoutMs() {
        return 10000;
    }

    public String getCallbackUrl() {
        return callbackUrl;
    }
}
